package org.mparts.client.activity;

import java.util.List;

import org.mparts.client.ui.events.ShowNewsEvent;
import org.mparts.client.utils.Utils;
import org.mparts.shared.MpartsRequestFactory;
import org.mparts.shared.proxy.AutoProxy;
import org.mparts.shared.proxy.PartgroupProxy;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.sencha.gxt.data.shared.ListStore;

public abstract class AbstractMpartsActivity extends AbstractActivity implements
		Presenter {

	protected MpartsRequestFactory rf;

	public abstract void start(AcceptsOneWidget panel, EventBus eventBus);

	@Override
	public void start(AcceptsOneWidget panel,
			com.google.gwt.event.shared.EventBus eventBus) {
		start(panel, (EventBus) eventBus);
		ShowNewsEvent event = new ShowNewsEvent(isShowNews());
		Log.debug("fire show news event: " + isShowNews());
		eventBus.fireEvent(event);
	}

	@Override
	public void loadLists(final ListStore<PartgroupProxy> partgroupStore,
			final ListStore<AutoProxy> autoStore) {
		if (Utils.getPartgroupList() != null) {
			partgroupStore.addAll(Utils.getPartgroupList());
		} else {
			if (rf != null) {
				Log.debug("request partgroups from server");
				rf.mpartsRequest().findAllPartgroups()
						.fire(new Receiver<List<PartgroupProxy>>() {

							@Override
							public void onSuccess(List<PartgroupProxy> response) {
								Utils.setPartgroupList(response);
								partgroupStore.addAll(response);
							}
						});
			}
		}

		if (Utils.getAutoList() != null) {
			autoStore.addAll(Utils.getAutoList());
		} else {
			if (rf != null) {
				Log.debug("request autos from server");
				rf.mpartsRequest().findAutos().with("models")
						.fire(new Receiver<List<AutoProxy>>() {

							@Override
							public void onSuccess(List<AutoProxy> response) {
								Utils.setAutoList(response);
								autoStore.addAll(response);
							}
						});
			}
		}

	}
	
	protected boolean isShowNews() {
		return false;
	}

}
